<?php


namespace App\Admin\Forms\Config;


use App\Models\Config\SystemConfig;
use App\Models\Config\SystemData;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

abstract class JsonConfigForm extends Form implements LazyRenderable
{
    use LazyWidget;

    abstract public static function label() :array;

    abstract public function form();

    abstract public function configKey() :string;

    abstract public function configName() :string;

    /**
     * 处理表单的提交
     * @param array $input
     * @return \Dcat\Admin\Http\JsonResponse
     */
    public function handle(array $input)
    {
        $labels = static::label();
        $config = SystemData::where("key",$this->configKey())->first();
        if(!$config){
            $config = SystemData::create(["key"=>$this->configKey(),"name"=>$this->configName()]);
        }
        $values = [];
        foreach ($labels as $key => $value){
            $values[$key] = Arr::get($input,$key);
        }
        $config->update(["value"=>json_encode($values)]);
        return $this->response()->success('设置成功');
    }

    /**
     * 表单默认值
     * @return mixed
     */
    public function default()
    {
        $value = [];
        $labels = static::label();
        $config = SystemData::where("key",$this->configKey())->first();
        if($config && $config->value){
            $values = json_decode($config->value,JSON_UNESCAPED_UNICODE);
            foreach ($labels as $key => $label){
                $value[$key] = Arr::get($values,$key);
            }
        }
        return $value;
    }


    public function savedScript()
    {
        return <<<'JS'
    if (data.status) {
        setTimeout(function () {
          location.reload()
        }, 1200);
    }
JS;
    }
}
